import os
from .models import *
import json
import datetime
import re
import hashlib
from django.db import connection
import csv
from urllib import parse
from django.forms.models import model_to_dict

'''


P5661,公交换乘,NOIp普及组,2019
P5662,纪念品,NOIp普及组,2019
P5663,加工零件,NOIp普及组,2019
P5660,数字游戏,NOIp普及组,2019

数字游戏
交通换乘
纪念品
零件加工
number
transfer
souvenir
work
'''
def importNoipTestCase():
    print('help')
    
    lgcsvfile = os.path.join('data', 'noip', 'lg.csv')
    ps = {}
    with open(lgcsvfile, 'r', encoding='utf-8') as lgf:
        lgcsv = csv.reader(lgf)
        for row in lgcsv:
            ps[row[1]] = {'pid': row[0], 'title': row[1], 'group': row[2], 'year': row[3]}


def importTestCase():
    datadir = os.path.join('data', 'noipdata')
    basedir = os.path.join('data', 'noip')
    csvfile = os.path.join(datadir, 'lg.csv')
    with open(csvfile, 'r', encoding='utf-8') as lgf:
        lgcsv = csv.reader(lgf)
        for row in lgcsv:
            _id = 'L' + row[0]
            casedir = os.path.join(basedir, _id)
            casedatadir = os.path.join(datadir, row[3], 'data', row[4])
            # 文件类型 in ans out
            fs = os.listdir(casedatadir)
            samples = []
            for f in fs:
                if f.lower().endswith('.in'):
                    infile = os.path.join(casedatadir, f) #os.path.join(casedatadir, f)
                    if os.path.exists(infile):
                        outfile = os.path.join(casedatadir, f[:-2] + 'ans')
                        if not os.path.exists(outfile):
                            outfile = os.path.join(casedatadir, f[:-2] + 'out')
                        if os.path.exists(outfile):
                            with open(infile, 'r', encoding='utf-8') as fr:
                                input = fr.read()
                            with open(outfile, 'r', encoding='utf-8') as fr:
                                output = fr.read()
                            samples.append({'input': input.rstrip(), 'output': output.rstrip()})
                        else:
                            print(outfile)
                    else:
                        print(infile)

            save_test_case(casedir, samples)
            print(len(samples))

def save_test_case(base_dir, test_casess):
    if not os.path.exists(base_dir):
        os.makedirs(base_dir)
    test_cases = {}
    index = 0
    for c in test_casess:
        input_content = c.get('input')
        output_content = c.get('output')
        output_content = re.sub(" *\\n", "\n", output_content)
        one_info = {
            "input_size": len(input_content),
            "input_name": f"{index + 1}.in",
            "output_size": len(output_content),
            "output_name": f"{index + 1}.out",
            "stripped_output_md5": hashlib.md5(output_content.rstrip().encode("utf-8")).hexdigest()
        }
        test_cases[index] = one_info
        with open(os.path.join(base_dir, str(index + 1) + ".in"), "w", encoding="utf-8") as f:
            f.write(input_content)
        with open(os.path.join(base_dir, str(index + 1) + ".out"), "w", encoding="utf-8") as f:
            f.write(output_content)
        index += 1
    info = {
        "spj": False,
        "test_cases": test_cases
    }
    with open(os.path.join(base_dir, "info"), "w", encoding="utf-8") as f:
        f.write(json.dumps(info, indent=4))

def loadCsv():
    lgcsvfile = os.path.join('data', 'noip', 'lg.csv')
    lgtagcsvfile = os.path.join('data', 'noip', 'lgtag.csv')

    ps = {}
    with open(lgcsvfile, 'r', encoding='utf-8') as lgf:
        lgcsv = csv.reader(lgf)
        for row in lgcsv:
            ps[row[0]] = {'pid': row[0], 'title': row[1], 'group': row[2], 'year': row[3]}

    with open(lgtagcsvfile, 'r', encoding='utf-8') as lgtagf:
        lgtagcsv = csv.reader(lgtagf)
        for row in lgtagcsv:
            ps[row[0]]['tags'] = row[2].split(",")

    return ps

def importSpecial():
    ps = loadCsv()
    spdic = {}
    for k in ps:
        p = ps[k]
        if p['year'] in spdic:
            spdic[p['year']].append(k)
        else:
            spdic[p['year']] = [k]
    oi = 30
    for k in spdic:
        group_name = 'noip'
        title = 'noip' + k
        ids = []
        for q in spdic[k]:
            ids.append('L' + q)
        qs = Problem.objects.filter(_id__in=ids)
        s = Special()
        s.title = title
        s.description = title
        s.problems_count = len(qs)

        oi += 1
        s.order_num = oi

        s.group_name = group_name
        s.create_time = datetime.datetime.now()
        
        print(json.dumps(model_to_dict(s), ensure_ascii=False))
        s.save()


        for p in qs:
            s.problems.add(p)


# 导入洛谷
def importNoip():

    tags = ProblemTag.objects.all()
    tagDic = {}
    for tag in tags:
        tagDic[tag.name] = tag

    ps = loadCsv()

    a_r = re.compile('<article>(.*?)</article>', re.S)
    title_r = re.compile('<h1>(.*?)</h1>')
    description_r = re.compile('<h2[^>]*>题目描述</h2>\\s*<div[^>]*>(.*?)</div>', re.S)
    input_description_r = re.compile('<h2[^>]*>输入格式</h2>\\s*<div[^>]*>(.*?)</div>', re.S)
    output_description_r = re.compile('<h2[^>]*>输出格式</h2>\\s*<div[^>]*>(.*?)</div>', re.S)
    hint_r = re.compile('<h2[^>]*>说明/提示</h2>\\s*<div[^>]*>(.*?)</div>', re.S)

    #<span data-v-83303c00="" class="key lfe-caption">时间限制</span> <span
    #data-v-83303c00="" class="value lfe-caption">1.00s</span>
    #<span data-v-83303c00="" class="key lfe-caption">内存限制</span> <span
    #data-v-83303c00="" class="value lfe-caption">125.00MB</span>
    time_limit_r = re.compile('>时间限制</span> <span [^>]*>([\\d\\.]*)s</span>')
    memory_limit_r = re.compile('>内存限制</span> <span [^>]*>([\\d\\.]*)MB</span>')

    json_content_r = re.compile('JSON\\.parse\\(decodeURIComponent\\("([^"]*)"')
    
    ct = 0

    for pid in ps:
        p = ps[pid]
        filename = pid + '.html'
        htmlfile = os.path.join('data', 'noip', filename)
        if os.path.exists(htmlfile):
            f = open(htmlfile, 'r', encoding='utf-8')
            html = f.read()
            f.close()
            uritxt_m = json_content_r.search(html)
            jsontxt = parse.unquote(uritxt_m.group(1))
            j = json.loads(jsontxt)
            pl = j['currentData']['problem']

            np = Problem()
            qid = pid
            np._id = 'L' + qid
            np.title = p['title']
                
            description = description_r.search(html)
            if description:
                np.description = description.group(1)
            else:
                np.description = ''
                
            input_description = input_description_r.search(html)
            if input_description:
                np.input_description = input_description.group(1)
            else:
                np.input_description = ''

            output_description = output_description_r.search(html)
            if output_description:
                np.output_description = output_description.group(1)
            else:
                np.output_description = ''

            np.solution = ''

            # [{input: "test", output: "123"}, {input: "test123", output:
            # "456"}]
            samples = []
            for s in pl['samples']:
                samples.append({'input': s[0].rstrip(), 'output': s[1].rstrip()})                    
            np.samples = json.dumps(samples)

            np.test_case_id = np._id
            save_test_case(os.path.join('data', 'noip', np._id), samples)

            hint = hint_r.search(html)
            if hint:
                np.hint = hint.group(1)
            else:
                np.hint = ''

            np.create_time = datetime.datetime.now()
            

            limits = pl['limits']

            np.time_limit = max(limits['time'])                          
            np.memory_limit = max(limits['memory']) / 1000

            np.visible = False
            np.submission_number = 0
            np.accepted_number = 0
            
            np.difficulty = str(pl['difficulty'])

            np.source = '洛谷'

            ct += 1

            print(json.dumps(model_to_dict(np), ensure_ascii=False))


            np.save()

            for qt in p['tags']:
                if qt in tagDic:
                    t = tagDic[qt]
                    np.tags.add(t)
